package youleche.com.controler.servlet;

import java.beans.IntrospectionException;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.text.ParseException;
import java.util.LinkedList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import youleche.com.business.BSeller;
import youleche.com.business.BUser;
import youleche.com.business.BVehicleInfo;
import youleche.com.common.ParamConfigParameters;
import youleche.com.controler.servlet.common.UlecheHttpServlet;
import youleche.com.model.MSeller;
import youleche.com.model.MUser;
import youleche.com.model.MVehicleInfo;
import youleche.com.util.AESEncryptAndDecrypt;
import youleche.com.util.JsonHelper;

/**
 * Servlet implementation class SAuthorityUserServlet
 */
public class CUserServletAuthority extends UlecheHttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CUserServletAuthority() {
        super();
    }

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		int action = Integer.parseInt(request.getParameter("action"));
		switch(action){
			case 0 :	
				//根据用户名获取车辆发布信息
				this.getVehiclesByUserName(request, response);
				break;	
			case 1:
				//根据商户Id获取发布信息的总数量
				this.getCountBySellerId(request, response);
				break;
			case 2:
				//用户修改密码
				this.modifyPass(request, response);
				break;
			case 3:
				//根据用户名得到用户信息
				this.getUserByUserName(request, response);
				break;	
			case 4:
				//申请成为商家
				this.becomeApplySeller(request, response);
				break;
			case 5 :
				//判断用户是否是商家
				this.isSeller(request, response);
				break;
			case 6 :
				//判断用户是否申请成为商家
				this.isApplySeller(request, response);
				break;
			case 7 :
				//获取商家总条数
				this.getSellerCount(request, response);
				break;
			case 8 :
				//获取商家列表
				this.getSellerList(request, response);
				break;
			case 9 :
				//获取申请商家总条数
				this.getApplySellerCount(request, response);
				break;
			case 10 :
				//获取申请商家列表
				this.getApplySellerList(request, response);
				break;
			case 11:
				//审核成为商家
				this.becomeSeller(request, response);
				break;
			case 12:
				//修改用户信息
				this.modifyUserInfoById(request, response);
				break;
		}		
	}
	
	/**
	 * 修改用户信息
	 * @param request
	 * @param response
	 */
	private void modifyUserInfoById(HttpServletRequest request, HttpServletResponse response){
		try {
			MUser user = (MUser)JsonHelper.getObjectByJsonStringAndGson(request, MUser.class);
			System.out.println(user.getA5());
			BUser handler = new BUser();
			handler.updateUserInfoById(user);
		} catch (Exception e) {
			e.printStackTrace();
		} 
	}
	
	/**
	 * 获取商家列表
	 * @param request
	 * @param response
	 */
	private void getSellerList(HttpServletRequest request, HttpServletResponse response){
		BUser handler = new BUser();
		int pageSize = Integer.parseInt(request.getParameter("pageSize"));
		Integer startIndex = (Integer.parseInt(request.getParameter("pageIndex")) - 1) * pageSize ;
		try {
			List<MUser> list = handler.getSellerList(startIndex.toString(), ((Integer)pageSize).toString());
			if(list == null || list.size() == 0){
				super.response(response, "");
				return;
			}

			List<MUser> handleList = new LinkedList<MUser>();
			ParamConfigParameters paramConfig = new ParamConfigParameters();
			String loginCode_KEY = paramConfig.getParameter("loginCode_KEY");
			for (MUser user : list) {
				user.setEmail(AESEncryptAndDecrypt.decrypt(user.getEmail(), loginCode_KEY));
				handleList.add(user);
			}
			
			JsonHelper.printListToJsonString(response, handleList);
		} catch (Exception e) {
			e.printStackTrace();
			super.response(response, "");
		}
	}
	
	/**
	 * 获取申请商家列表
	 * @param request
	 * @param response
	 */
	private void getApplySellerList(HttpServletRequest request, HttpServletResponse response){
		BUser handler = new BUser();
		int pageSize = Integer.parseInt(request.getParameter("pageSize"));
		Integer startIndex = (Integer.parseInt(request.getParameter("pageIndex")) - 1) * pageSize ;
		try {
			List<MUser> list = handler.getApplySellerList(startIndex.toString(), ((Integer)pageSize).toString());
			if(list == null || list.size() == 0){
				super.response(response, "");
				return;
			}

			List<MUser> handleList = new LinkedList<MUser>();
			ParamConfigParameters paramConfig = new ParamConfigParameters();
			String loginCode_KEY = paramConfig.getParameter("loginCode_KEY");
			for (MUser user : list) {
				user.setEmail(AESEncryptAndDecrypt.decrypt(user.getEmail(), loginCode_KEY));
				handleList.add(user);
			}
			
			JsonHelper.printListToJsonString(response, handleList);
		} catch (Exception e) {
			e.printStackTrace();
			super.response(response, "");
		}
	}
	
	/**
	 * 获取商家总条数
	 * @param request
	 * @param response
	 */
	private void getSellerCount(HttpServletRequest request, HttpServletResponse response){
		BUser handler = new BUser();
		try {
			super.response(response, ""+handler.getSellerCountByA4_Status("1")+"");
		} catch (Exception e) {
			super.response(response, "0");
			e.printStackTrace();
		}
	}
	
	/**
	 * 获取申请商家总条数
	 * @param request
	 * @param response
	 */
	private void getApplySellerCount(HttpServletRequest request, HttpServletResponse response){
		BUser handler = new BUser();
		try {
			super.response(response, ""+handler.getSellerCountByA4_Status("1.5")+"");
		} catch (Exception e) {
			super.response(response, "0");
			e.printStackTrace();
		}
	}
	
	/**
	 *判断用户是否申请成为商家
	 * @param request 请求
	 * @return 返回页面参数
	 */
	private void isApplySeller(HttpServletRequest request, HttpServletResponse response){
		String userName = request.getParameter("userName");
		BUser handler = new BUser();
		try {
			MUser user = handler.getUserByUserName(userName);
			if(user != null && !"".equals(user.getEmail())){
				if(handler.isApplySellserByEmail(user.getEmail())){
					super.response(response, "1");
					return;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			super.response(response, "0");
		}
		
		super.response(response, "0");
	}
	
	/**
	 *判断用户是否是商家
	 * @param request 请求
	 * @return 返回页面参数
	 */
	private void isSeller(HttpServletRequest request, HttpServletResponse response){
		String userName = request.getParameter("userName");
		BUser handler = new BUser();
		try {
			MUser user = handler.getUserByUserName(userName);
			if(user != null && !"".equals(user.getEmail())){
				if(handler.isSellserByEmail(user.getEmail())){
					super.response(response, "1");
					return;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			super.response(response, "0");
		}
		
		super.response(response, "0");
	}
	
	/**
	 * 用户申请成为商家
	 * @param request 请求
	 * @return 返回页面参数
	 */
	private void becomeSeller(HttpServletRequest request, HttpServletResponse response){
		String email = request.getParameter("email");	
		BUser handler = new BUser();
		try {
			ParamConfigParameters paramConfig = new ParamConfigParameters();
			String loginCode_KEY = paramConfig.getParameter("loginCode_KEY");
			if(handler.becomeSellerByEmail(AESEncryptAndDecrypt.encrypt(email, loginCode_KEY)) > 0){
				MUser user = handler.getUserByUserName(handler.getUserNameByEmailAccount(AESEncryptAndDecrypt.encrypt(email, loginCode_KEY)));
				MSeller seller = new MSeller();
				seller.setUserId(user.getId());
				seller.setIsDelete("0");
				seller.setShopAddress("0");
				seller.setShopImgUrl("0");
				seller.setShopName("0");
				BSeller sellerHandler = new BSeller();
				sellerHandler.addSellerInfo(seller);
				
				super.response(response, "1");
				return;
			}
		} catch (Exception e) {
			e.printStackTrace();
			super.response(response, "0");
		}
		super.response(response, "0");
	}
	
	/**
	 * 用户申请成为商家
	 * @param request 请求
	 * @return 返回页面参数
	 */
	private void becomeApplySeller(HttpServletRequest request, HttpServletResponse response){
		String email = request.getParameter("email");		
		String phone = request.getParameter("phone");	
		BUser handler = new BUser();
		try {
			ParamConfigParameters paramConfig = new ParamConfigParameters();
			String loginCode_KEY = paramConfig.getParameter("loginCode_KEY");
			handler.updatePhoneByEmail(AESEncryptAndDecrypt.encrypt(email, loginCode_KEY), phone);
			if(handler.applyBecomeSellerByEmail(AESEncryptAndDecrypt.encrypt(email, loginCode_KEY)) > 0){
				super.response(response, "1");
				return;
			}
		} catch (Exception e) {
			e.printStackTrace();
			super.response(response, "0");
		}
		super.response(response, "0");
	}
	/**
	 * 根据用户名得到用户信息
	 * @param request
	 * @param response
	 */	
	private void getUserByUserName(HttpServletRequest request, HttpServletResponse response){
		String userName = request.getParameter("userName");
		BUser handler = new BUser();
		try {
			MUser user = handler.getUserByUserName(userName);
			if(user != null){
				ParamConfigParameters paramConfig = new ParamConfigParameters();
				String loginCode_KEY = paramConfig.getParameter("loginCode_KEY");
				user.setUserPassword("");
				user.setEmail(AESEncryptAndDecrypt.decrypt(user.getEmail(), loginCode_KEY));
				
				//user.setPhoneNum(AESEncryptAndDecrypt.decrypt(user.getPhoneNum(), loginCode_KEY));
				JsonHelper.printObjectToJsonString(response, user);
			}else{
				super.response(response, "");
			}
		} catch (Exception e) {
			e.printStackTrace();
			super.response(response, "");
		}
	}
	
	/**
	 * 用户修改密码
	 * @param request
	 * @param response
	 */	
	private void modifyPass(HttpServletRequest request, HttpServletResponse response){
		String userName = request.getParameter("userName");
		BUser handler = new BUser();
		try {
			MUser user = handler.getUserByUserName(userName);
			if(user == null){
				super.response(response, "0");
				return;
			}
			
			ParamConfigParameters paramConfig = new ParamConfigParameters();
			String loginCode_KEY = paramConfig.getParameter("loginCode_KEY");
			String oldPass = request.getParameter("oldpass");
			oldPass = AESEncryptAndDecrypt.encrypt(oldPass, loginCode_KEY);
			if(!oldPass.equals(user.getUserPassword())){
				super.response(response, "1");
				return;
			}
			
			String newpass = AESEncryptAndDecrypt.encrypt(request.getParameter("newpass"), loginCode_KEY);
			
			if(newpass.equals(oldPass)){
				super.response(response, "2");
				return;
			}
			
			if(handler.updatePasswordByUserName(userName, newpass) > 0){
				super.response(response, "2");
			}else{
				super.response(response, "3");
			}
		} catch (Exception e) {
			e.printStackTrace();
			super.response(response, "0");
		}
	}
	
	/**
	 * 根据商户Id获取发布信息的总数量
	 * @param request
	 * @param response
	 */	
	private void getCountBySellerId(HttpServletRequest request, HttpServletResponse response){
		String userName = request.getParameter("userName");
		BUser handler = new BUser();
		try {
			MUser user = handler.getUserByUserName(userName);
			if(user != null){
				BVehicleInfo handlerInfo = new BVehicleInfo();
				super.response(response, ((Integer)handlerInfo.getCountBySellerId(user.getId())).toString());
				return;
			}
			
			super.response(response, "");
		} catch (Exception e) {
			e.printStackTrace();
			super.response(response, "");
		}
	}
	
	/**
	 * 根据用户名获取车辆发布信息
	 * @param request
	 * @param response
	 */	
	private void getVehiclesByUserName(HttpServletRequest request, HttpServletResponse response){
		String userName = request.getParameter("userName");
		BUser handler = new BUser();
		try {
			MUser user = handler.getUserByUserName(userName);
			if(user != null){
				String userId = user.getId();
				int pageSize = Integer.parseInt(request.getParameter("pageSize"));
				Integer startIndex = (Integer.parseInt(request.getParameter("pageIndex")) - 1) * pageSize ;
				BVehicleInfo handlerInfo = new BVehicleInfo();
				List<MVehicleInfo> infos = handlerInfo.getVehicleInfoBySellerId(userId, startIndex.toString(), ((Integer)pageSize).toString());
				if(infos != null && infos.size() > 0){					
					JsonHelper.printListToJsonString(response, infos);
					return;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		super.response(response, "");
	}

}
